import { useState, useEffect } from 'react'
import { message } from 'antd'
import { CopyOutlined, SyncOutlined } from '@ant-design/icons'
import styles from './index.module.scss'

const QuoteCard = () => {
  const [quote, setQuote] = useState({
    content: '加载中...',
    author: '',
    pic_url: '',
    date: new Date().toLocaleDateString(),
    loading: true
  })

  // 获取每日一言
  const fetchQuote = async () => {
    setQuote(prev => ({ ...prev, loading: true }))
    try {
      const signatureKey = `U2FsdGVkX1${Date.now()}`
      
      const response = await fetch('https://api.codelife.cc/yiyan/info?lang=cn', {
        headers: {
          'signaturekey': signatureKey,
          'origin': window.location.origin
        }
      })
      
      const result = await response.json()
      
      if (result.msg === '请求成功') {
        const data = result.data
        setQuote({
          content: data.content || '今日无一言',
          author: data.author || '未知',
          pic_url: data.pic_url || '',
          date: data.date,
          loading: false
        })
      }
    } catch (error) {
      console.error('每日一言获取失败:', error)
      setQuote({
        content: '',
        author: '',
        pic_url: '',
        date: new Date().toLocaleDateString(),
        loading: false
      })
    }
  }

  // 复制一言
  const handleCopy = () => {
    navigator.clipboard.writeText(`${quote.content}——${quote.author || ''}`)
      .then(() => message.success('已复制到剪贴板'))
      .catch(() => message.error('复制失败'))
  }

  useEffect(() => {
    fetchQuote()
  }, [])

  return (
    <div className={styles['quoteCard']} style={{ backgroundImage: `url(${quote.pic_url})` }}>
      <p className={styles['title']}>每日一言</p>
      <p className={styles['content']}>{quote.content}</p>
      {quote.author && (
        <p className={styles['author']}>——{quote.author}</p>
      )}
      {!quote.content && (
        <p className={styles['content']} onClick={fetchQuote}>每日一言加载失败，点击刷新</p>
      )}
    </div>
  )
}

export default QuoteCard